package com.example.email.config;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * 邮件发送
 */
@Component
public class MailComponent {
    private static final Logger logger= LoggerFactory.getLogger(MailComponent.class);


    @Autowired
    private MailConfiguration mailConfiguration;

    /**
     * 发送邮件
     *
     * @param to   接收人
     * @param text 发送内容
     * @Description: 发送邮件
     */
    public void sendMail(String to, String subject, String text) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("email", to);
        try {
            send(to, subject, text);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
        }
    }

    private String send(String email, String subject, String text) throws UnsupportedEncodingException, javax.mail.MessagingException {
        MimeMessage message = mailConfiguration.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        InternetAddress from = new InternetAddress();
        from.setAddress(mailConfiguration.getUsername());
        from.setPersonal(mailConfiguration.getUsername(), "UTF-8");
        helper.setFrom(from);
        helper.setTo(email);
        helper.setSubject(subject);
        helper.setText(text, true);
        mailConfiguration.send(message);
        logger.info("发送人: " + mailConfiguration.getUsername());
        logger.info("接收人: " + email);
        logger.info("发送主题: " + subject);
        logger.info("发送内容: " + text);
        return text;
    }
}

